import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Modal, Button, Typography, Alert } from 'antd';
import { StepBackwardOutlined } from '@ant-design/icons';

const { Title } = Typography;
const { ErrorBoundary } = Alert;

const ErrorBoundaryDialog = ({ context, children }) => {
  const handleOnError = (error, componentStack) => {
    const ErrorDialog = () => {
      const [open, setOpen] = useState(false);

      return (
        <div className="ErrorFallback" role="alert">
          <Title level={3}>
            {context}: <span>{error.message}</span>
          </Title>
          <Button icon={<StepBackwardOutlined />} onClick={() => setOpen(s => !s)}>
            Stack Trace
          </Button>

          {open && <pre>{componentStack}</pre>}
        </div>
      );
    };

    Modal.error({
      content: ErrorDialog,
      title: `Something went wrong in ${context}`,
    });
  };

  const fallbackComponent = () => (
    <div className="ErrorFallback" role="alert">
      <p>
        Error rendering {context}. <br /> Check the browser console for more
        details.
      </p>
    </div>
  );

  return (
    <ErrorBoundary
      fallbackComponent={fallbackComponent}
      onError={handleOnError}
    >
      {children}
    </ErrorBoundary>
  );
};

ErrorBoundaryDialog.propTypes = {
  children: PropTypes.node.isRequired,
};

export default ErrorBoundaryDialog;
